package org.redis.cluster.transport.support;

import org.redis.cluster.transport.ByteBuffer;

public class ReplayingByteBuffer implements ByteBuffer {
	
	private ByteBuffer byteBuffer;
	
	public ReplayingByteBuffer(ByteBuffer byteBuffer) {
		this.byteBuffer=byteBuffer;
	}

	@Override
	public byte[] array() {
		return byteBuffer.array();
	}

	@Override
	public boolean skip(int length) {
		checkIsReadable(length);
		return byteBuffer.skip(length);
	}

	@Override
	public byte getByte(int position) {
		return byteBuffer.getByte(position);
	}

	@Override
	public int readableBytes() {
		return byteBuffer.readableBytes();
	}

	@Override
	public boolean isReadable() {
		return byteBuffer.isReadable();
	}

	@Override
	public boolean isReadable(int length) {
		return byteBuffer.isReadable(length);
	}

	@Override
	public byte readByte() {
		checkIsReadable(1);
		return byteBuffer.readByte();
	}

	@Override
	public boolean readBytes(byte[] bytes) {
		checkIsReadable(bytes.length);
		return byteBuffer.readBytes(bytes);
	}

	@Override
	public int position() {
		return byteBuffer.position();
	}

	@Override
	public boolean position(int newPosition) {
		return byteBuffer.position(newPosition);
	}
	
	protected void checkIsReadable(int length) {
		if(readableBytes()>=length) {
			return;
		}
		
		throw new ReplayingException();
	}
}